package org.lys.jdbc.beta.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.lys.jdbc.beta.RowMapper;
import org.lys.jdbc.beta.dao.UserDao;
import org.lys.jdbc.domain.User;

public class UserDaoJdbcImpl extends BaseDaoImpl implements UserDao {

	@Override
	public User find(String loginName, String password) {
		String sql = "select id, name, money, birthday  from user where name=?";
		Object[] args = new Object[] { loginName };
		Object user = super.findForObject(sql, args,new RowMapper() {
			@Override
			public Object rowMapper(ResultSet rs) throws SQLException {
				User user = new User();
				user.setId(rs.getInt("id"));
				user.setName(rs.getString("name"));
				user.setMoney(rs.getFloat("money"));
				user.setBirthday(rs.getDate("birthday"));
				return user;
			}
		});
		return (User) user;
	}

	@Override
	public void add(User user) {
		if(user==null){
			return;
		}
		String sql = "insert into user(name,birthday, money) values (?,?,?) ";
		Object[] params = new Object[] { user.getName(),user.getBirthday(),user.getMoney() };
		super.add(sql, params);
	}

	@Override
	public void delete(User user) {
		if(user==null){
			return;
		}
		String sql = "delete from user where id=?";
		Object[] params = new Object[] { user.getId() };
		super.delete(sql, params);
	}

	@Override
	public void update(User user) {
		if(user==null){
			return;
		}
		String sql = "update user set name=?, birthday=?, money=? where id=? ";
		Object[] params = new Object[] { user.getName(),user.getBirthday(),user.getMoney(),user.getId() };
		super.update(sql, params);
	}

	@Override
	public User get(int userId) {
		String sql = "select id, name, money, birthday  from user where id=?";
		Object[] args = new Object[] { userId };
		Object user = super.findForObject(sql, args,new RowMapper() {
			@Override
			public Object rowMapper(ResultSet rs) throws SQLException {
				User user = new User();
				user.setId(rs.getInt("id"));
				user.setName(rs.getString("name"));
				user.setMoney(rs.getFloat("money"));
				user.setBirthday(rs.getDate("birthday"));
				return user;
			}
		});
		return (User) user;
	}

	@Override
	public Long addRtnPk(User user) {
		String sql = "insert into user(name,birthday, money) values (?,?,?) ";
		Object[] params = new Object[] { user.getName(),user.getBirthday(),user.getMoney() };
		return (Long) super.addRtnPk(sql, params);
	}


}
